# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  #  before_filter :set_wap_content_type,:only => [:wap,:col,:user_cfg]
  # before_filter :adjust_format_for_beta
  before_filter :configure_charsets,:except => [:wap,:col,:user_cfg]
  helper :all # include all helpers, all the time
  protect_from_forgery :only => [:create, :update, :destroy]
    
  def configure_charsets
    #@headers["Content-Type"] = "text/html; charset=utf-8"
    response.headers["Content-Type"] = "text/html; charset=utf-8"
    # Set connection charset. MySQL 4.0 doesn’t support this so it
    #will throw an error, MySQL 4.1 needs this
    suppress(ActiveRecord::StatementInvalid) do
      ActiveRecord::Base.connection.execute 'SET NAMES utf8'
    end
  end

  #  def set_wap_content_type
  #    response.headers["Cache-Control"] = "no-cache"
  #    response.headers["Content-Type"] = "text/vnd.wap.wml;charset=UTF-8"
  #  end

  #  def adjust_format_for_beta
  #    request.format = :beta if beta_request?
  #  end

  #  def beta_request?
  #    return (request.subdomains.first == "beta" || params[:format] == "beta")
  #  end

  #定义一个auth方法来检查用户是否登陆，并保存用户最初请求的URL
  def auth
    if session['user'].nil?
      session['last_url'] = request.request_uri
      redirect_to :controller => 'user' , :action => 'login'
    end
  end

  #过滤器，判断是否有sid,没有则生成一个
  #根据来源域名不同设置不同的栏目和资源  
  def set_cookies_or_url   
    begin
      unless params[:fr].nil?
        value = params[:fr]
        fr = Fr.find_last_by_value value
        unless fr.nil?
          fr_stat = FrStat.new
          fr_stat.fr_id = fr.id
          fr_stat.name = fr.name
          fr_stat.value = fr.value
        else
          fr_stat = FrStat.new
          fr_stat.name = "未配置推广来源"
          fr_stat.value = value
        end
        fr_stat.save
        params[:fr] = nil
      end
    rescue
    end

    if $level_map.length() ==0
      Level.set_level_map
    end
    
    if params[:sid].nil?
      if cookies[:sid].nil?
        params[:sid] = get_sid        
        cookies['sid'] = { :value => params[:sid], :expires => 1.year.from_now }
      else       
        params[:sid] = cookies[:sid]       
      end    
    end    

    #判断sid的生成时间
    user_cfg = UserCfg.find_last_by_sid params[:sid]    
    if !user_cfg.nil? && user_cfg.created_at.strftime("%Y-%m-%d") <= (Time.now - 24*60*60).strftime("%Y-%m-%d")
      if user_cfg.user_type == '0'       
        user_cfg.update_attributes({:updated_at => Time.now,:user_type => '1'})
      end
    end
    if user_cfg.nil?
      user_cfg = UserCfg.new
      user_cfg.sid = params[:sid]
      us = UserCfg.find :all,:order => 'user_sign desc',:limit => '1'
      if us.size < 1
        sign = 9999
      else
        sign = us[0].user_sign.to_i
        if sign < 10000
          sign = 9999
        end
      end
      user_cfg.user_sign = sign + 1
      user_cfg.save
    end
    
    #url中带的参数不全则查询数据库设置一遍参数
    if params[:img_style].nil? || params[:img_style].to_i == 0 || params[:pp_style].nil? || params[:pp_style].to_i == 0 || params[:pp_num].nil? || params[:pp_num].to_i == 0
      user_cfg = UserCfg.find_last_by_sid params[:sid]
      params[:img_style] = user_cfg.img_style
      params[:pp_style] = user_cfg.pp_style
      params[:pp_num] = user_cfg.pp_num
    end    
    if params[:cn].nil? || user_cfg.guide_status == '1'
      params[:cn] = 0
      user_cfg.update_attributes({:guide_status => '0'})
    end

    #判断请求的action
    re_action = request.path_parameters[:action]    
    click_res_num = params[:cn].to_i
    if $ad_map.length == 0
      $ad_map.clear
      $ad_map['5'] = 30
      $ad_map['10'] = 50
      $ad_map['20'] = 80
    end
    if re_action == 'show_small' || re_action == 'show_big'
      if is_guide click_res_num
        ge = get_guide_url
        unless ge.nil?
          url = ge.guide_url
          params[:cn] = 0
          user_cfg.update_attributes({:guide_status => '1'})
          redirect_to url
        end
      end
    end
    #    redirect_to params.merge!(:controller=>re_controller,:action => re_action)
  end

  #导量的url
  def get_guide_url    
    ge = nil    
    ges = GuideExec.find_by_sql("select * from guide_execs as ge where date_format(ge.created_at,'%Y-%m-%d') = '#{Time.now.strftime('%Y-%m-%d')}' and ge.status <>'3' order by rand() limit 1")
    if ges.size < 1
      GuideExec.set_guide_other
      ges = GuideExec.find_by_sql("select * from guide_execs as ge where date_format(ge.created_at,'%Y-%m-%d') = '#{Time.now.strftime('%Y-%m-%d')}' and ge.status <>'3' order by rand() limit 1")
    end
    if ges.size > 0
      ge = ges[0]
      if ge.out_num.to_i >= ge.need_num
        ge.update_attributes({:out_num => (ge.out_num.to_i),:status => 3})        
        ge = nil
      else
        ge.update_attributes({:out_num => (ge.out_num.to_i + 1),:status => 1})
      end
    end  
    return ge
  end

  #根据几率得到是否能导量ss
  def is_guide cn
    cc = 0
    if cn > 8 && cn < 15
      cc = $ad_map['5'].to_i
    elsif cn >= 15 && cn < 25
      cc = $ad_map['10'].to_i
    elsif cn >= 25
      cc = $ad_map['20'].to_i
    end
    rs = []
    if cc == 30
      rs = rand_get(9,1)
    end
    if cc == 50
      rs = rand_get(7,1)
    end
    if cc == 80
      rs = rand_get(5,1)
    end
    flag = false    
    rs.each do |i|
      if i.to_i == 0
        flag = true
      end
    end
    return flag
  end
 

  #得到sid
  def get_sid
    arraySrc = ['Q','6','e','T','u','O','s','F','h','K','m',
      '4','B','c','Z','x','0','V','n','L','8','j','G','d','A',
      'w','9','R','y','I','1','p','r','v','f','Y','g','N','b',
      't','U','i','J','2','M','l','k','z','3','S','a','W','q','E','D','5',
      'X','C','P','o','H','7']
    rands = rand_get(61, 10)
    sid = ""
    rands.each do |i|
      sid = sid + arraySrc[i]
    end
    return sid
  end

  #记录日志filter
  def log_filter
    log = Log.new
    log.sid = params[:sid]
    log.type = @oper_type.to_s
    log.name = case log.type
    when "1"
      "首页访问"
    when "2"
      "书签访问"
    when "3"
      "栏目访问"
    when "4"
      "大图浏览"
    when "5"
      "小图浏览"
    when "6"
      "标签访问"
    when "7"
      "广告"
    when "11"
      "千变"
    when "99"
      "留言"
    else
      "其它"
    end
    log.desc = case log.type
    when "1"
      "点击首页"
    when "2"
      "点击书签"
    when "3"
      @col.name
    when "4"
      @resource.name
    when "5"
      @resource.name
    when "6"
      @tg.name
    when "7"
      "广告"
    when "11"
      "千变"
    when "99"
      @msg
    else
      "其它"
    end
    log.save
  end

  #随机种子
  def rand_get(n, m)
    if m.zero?
      []
    else
      s = rand_get(n-1, m-1)
      t = rand(n+1)
      s.concat s.include?(t) ? [n] : [t]
    end
  end

  #wap页面的分页
  def paginate_wap(collection, options = {})
    default_options = {:per_page => 2, :page => 1}
    options = default_options.merge options
    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end

  #导量判断
  def export_ad()
    sid = params[:sid]
    user_cfg = UserCfg.find_last_by_sid sid
    puts "-------#{user_cfg.click_num}"
  end


  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
end
